package com.czn.shopdemo.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author Zenan Chen
 * @date 2023/4/4 9:40
 */
public class JwtUtil {

    private static long tokenExpiration = 24 * 60 * 60 * 1000;
    private static String tokenSignKey = "chenzn15";

    public static String createToken(Long userId, String userName) {
        String token = Jwts.builder().setSubject("SHOP-DEMO").setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).claim("userId", userId).claim("userName", userName).signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
        return token;
    }

    public static Long getUserId(String token) {
        if (StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer) claims.get("userId");
        return userId.longValue();
    }

    public static String getUserName(String token) {
        if (StringUtils.isEmpty(token)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("userName");
    }

    public static void main(String[] args) {
        String token = JwtUtil.createToken(1L, "chenzn");
        System.out.println(token);
        System.out.println(JwtUtil.getUserId(token));
        System.out.println(JwtUtil.getUserName(token));
    }
}
